<template>
  <div>
      <MyFormCreate v-model="searchForm" :rule="searchFormRules" :key="key">
        <template #field-productId="scope">
          <el-select clearable @clear="getTableList" v-model="searchForm.productId" :placeholder="prompt?.productId"
            :teleported="false" @change="v => scope.data.model.callback(v)">
            <el-option v-for="item in productTypes" :key="item.productId" :label="item.productName"
              :value="item.productId"></el-option>
          </el-select>
        </template>
        <template #field-createdAt="scope">
          <el-form-item>
            <el-date-picker type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
              value-format="YYYY-MM-DD" placeholder="请选择创建时间" style="width: 100%" v-model="searchForm.createdAt"
              :teleported="false" @change="dateChange" />
          </el-form-item>
        </template>
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <div>
        <!-- <sj-button type="primary" :icon="Plus" @click="add">添加</sj-button>
        <el-button type="danger" :icon="Delete" :disabled="!selectionData.length" @click="deletes()">批量删除</el-button> -->
      </div>
      <pure-table :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)"
        showOverflowTooltip @selection-change="selectionChange" :isShowPag="false">
        <template #dealStatus="{ row }">
          <el-tag :type="HANDLESTATUSTEXT[row.dealStatus]?.type" :key="row.dealStatus">
            {{ isNullOrEmpty(HANDLESTATUSTEXT[row.dealStatus]?.label) }}
          </el-tag>
          <!-- {{ isNullOrEmpty( HANDLESTATUSTEXT[row.dealStatus]?.label ) }} -->
        </template>
        <template #confirm="{ row }">
          <el-tag :type="CONFIRMSTATUSTEXT[row.confirm]?.type" :key="row.confirm">
            {{ isNullOrEmpty(CONFIRMSTATUSTEXT[row.confirm]?.label) }}
          </el-tag>
          <!-- {{ isNullOrEmpty( CONFIRMSTATUSTEXT[row.confirm]?.label ) }} -->
        </template>

        <template #alarmType="{ row }">
          <el-tag :type="ALARMTYPES[row.alarmType]?.type" :key="row.alarmType">{{ ALARMTYPES[row.alarmType]?.label
            }}</el-tag>
          <!-- {{ isNullOrEmpty( ALARMTYPES[row.alarmType]?.label ) }} -->
        </template>
        <template #action="{ row }">
          <el-space class="mr-[5px]">
            <sj-link custom-type="sblue" :underline="false" @click="showIndividualityAlarmInfo(row)">详情</sj-link>
          </el-space>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
  </div>
</template>
<script lang="ts" setup>
import { showIndividualityAlarmInfo } from '../../utils/index'
import { isNullOrEmpty, initPureTableConfig } from '@/utils/functions'
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import alarmHand from '@/views/large-data-screen/component/alarmHand.vue'
import { reactive, ref } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { getList } from '@/api/screen/alarm/index';
import { titles, defaultSearchForm, prompt } from './index';
import { debounce } from "@pureadmin/utils";
import { CONFIRMSTATUS, CONFIRMSTATUSTEXT, HANDLESTATUSTEXT, HANDLESTATUS, ALARMTYPE, ALARMTYPES } from "@/constant/alarm-mangenment";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import { getAlarmHandle, getProductType } from "@/api/screen";
import alarminfo from "@/views/large-data-screen/component/alarm/alarm-info.vue"
import { getInfo } from "@/api/screen/alarm/index";
import { defaultInfoForm } from "@/views/operate/alarm-management/alarm-log/index"

const props = defineProps({
  defaultSearch: {
    type: Object,
    default: null
  }
})

const searchForm = ref(defaultSearchForm());
const key = ref(0);
const formRef = ref()
const productTypes = ref([]);
const tableData = reactive({
  data: [],
  total: 0,
});

const searchFormRules = [
  {
    type: 'input', field: 'deviceId', title: titles.deviceId, value: null, props: {
      placeholder: prompt.deviceId, clearable: true
    }
  },
  {
    type: 'input', field: 'alarmTitle', title: titles.alarmTitle, value: null, props: {
      placeholder: prompt.alarmTitle, clearable: true
    }
  },
  {
    type: 'select', field: 'confirm', title: titles.confirm, value: null,
    options: CONFIRMSTATUS,
    props: {
      placeholder: prompt.confirm, clearable: true, teleported: false
    }
  },
  {
    type: 'fieldComponent', field: 'productId', title: titles.productId, value: null, props: {
      placeholder: prompt.productId, clearable: true
    }
  },
  {
    type: 'fieldComponent', field: 'createdAt', title: titles.createdAt, value: null, props: {
      placeholder: prompt.createdAt, clearable: true
    }
  },
  {
    type: 'select', field: 'alarmType', title: titles.alarmType, value: null,
    options: ALARMTYPE,
    props: {
      placeholder: prompt.alarmType, clearable: true, teleported: false
    }
  },
  {
    type: 'input', field: 'nickname', title: titles.nickname, value: null,
    props: {
      placeholder: prompt.nickname, clearable: true, teleported: false
    }
  },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];
const selectionData = ref([]);
const roleTableConfig = [
  // { type: "selection", align: "left", fixed: 'left' },
  { prop: "id", label: titles.id, width: 100, fixed: 'left' },
  { prop: "unityName", label: "所属单位", minWidth: 100,showOverflowTooltip:true  },
  { prop: "nickname", label: "所属个体", minWidth: 100 },
  { prop: "familyName", label: "所属家庭", minWidth: 100 },
  { prop: "roomName", label: "所属房间", minWidth: 100 },
  // { prop: "place", label: titles.place, minWidth: 100 },
  // { prop: "projectName", label: titles.projectName, minWidth: 150 },
  { prop: "productName", label: titles.productName, minWidth: 100 ,showOverflowTooltip:true },
  { prop: "deviceSN", label: titles.deviceSN, minWidth: 100 },
  { prop: "alarmTitle", label: titles.alarmTitle, minWidth: 100 ,showOverflowTooltip:true },
  // { slot: "confirm", label: titles.confirm, minWidth: 90 },
  // { slot: "alarmType", label: titles.alarmType, minWidth: 90 },
  // { slot: "dealStatus", label: titles.dealStatus, minWidth: 100 },
  { prop: "createdAt", label: titles.createdAt, minWidth: 180 },
  { slot: "action", label: titles.action, width: 90, fixed: "right" }
];
onMounted(() => {
  if (props.defaultSearch) {
    let searchRule = searchFormRules.map(item => item.field)
    for (const key in props.defaultSearch) {
      if (!searchRule.includes(key)) {
        searchFormRules.push({ type: '', field: key, title: key, hidden: true })
      }
      searchForm.value[key] = props.defaultSearch[key];
    }
    key.value = Math.floor(Math.random() * 1000)
  }
  getTableList()
  getProductType().then(res => {
    if (res.code === 200) {
      productTypes.value = res.result;
      key.value++;
    }
  })
});

const info = (row: any) => {
  addDialog({
    title: `告警详情`,
    width: "800px",
    draggable: true,
    fullscreen: false,
    fullscreenIcon: true,
    props: {
      id: row.id
    },
    hideFooter: true,
    closeOnClickModal: false,
    contentRenderer: () => h(alarminfo, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        id: row.id,
        formInline: defaultInfoForm()
      };
      getInfo({ id: row.id }).then(res => {
        if (res.code == 200) {
          options.props.formInline = res.result;
          // options.props.id = res.result.deviceId;
        }
        options.props.isLoading = false;
      });
    }
  });
};
// 获取列表数据
const getTableList = () => {
  getList(searchForm.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchForm.value, defaultSearchForm())
  key.value++
  getTableList()
}
const defour = (id) => {
  return {
    id: id,
    confirm: null,
    dealStatus: null,
    dealView: null,
    sellMethod: null,
    processId: null,
    handleUid: null,
    noticeType: []
  };
};
// 处理
const handling = (row) => {
  addDialog({
    title: `告警处理`,
    width: "400px",
    draggable: true,
    fullscreen: false,
    fullscreenIcon: true,
    props: {
      id: row.id,
      projectId: row.projectId,
    },
    closeOnClickModal: false,
    contentRenderer: () => h(alarmHand, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: false,
        id: row.id,
        projectId: row.projectId,
        formInlines: defour(row.id)
      };
    },
    beforeSure: (done, { options }) => {
      const FormRefsa = formRef.value.getRef();
      const formData = options.props.formInlines;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done();
        getTableList();
      }
      console.log("formData", formData);

      FormRefsa.validate(valid => {
        if (valid) {
          getAlarmHandle(formData).then(res => {
            if (res.code == 200) {
              chores()
            }
          }).catch(err => {
            if (err !== "请求中") {
              options.props.isLoading = false;
            }
          });
        }
      });
    }
  });
}

const dateChange = e => {
  searchForm.value.startTime = e[0];
  searchForm.value.endTime = e[1];
};
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
</script>
<style lang="scss" scoped></style>
